<?php

/*
 *    author:		Kyle Gadd
 *    documentation:	http://www.php-ease.com/wordpress/themes/framework.html
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class WPage {

  private $title = '';
  private $description = '';
  private $keywords = '';
  private $robots = true;
  private $doctype = '<!DOCTYPE html>';
  private $xhtml = false;
  private $include = array();
  private $css = array();
  private $jquery = array();
  private $body = '';
  private $errors = array();
  public $vars = array();

  function __construct ($title='') {
    if (empty($title)) {
      $title = wp_title('|', false, 'right') . get_bloginfo('name');
      $description = get_bloginfo('description', 'display');
      if ($description && (is_home() || is_front_page())) {
        $title .= ' | ' . $description;
      }
    }
    $this->title = $title;
    ob_start("ob_gzhandler"); // used in $this->capture()
    if (is_singular() && get_option('thread_comments')) $this->link('comment-reply.js');
  }

  public function doctype ($type='html', $standard='strict') {
    if (in_array($standard, array('strict', 'transitional'))) {
      if ($type == 'html') {
        $this->xhtml = false;
        switch ($standard) {
          case 'strict': $this->doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'; break;
          case 'transitional': $this->doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'; break;
        }
      } elseif ($type == 'xhtml') {
        $this->xhtml = true;
        switch ($standard) {
          case 'strict': $this->doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; break;
          case 'transitional': $this->doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'; break;
        }
      }
    }
  }

  public function title ($title='') {
    if (!empty($title)) $this->title = $title;
    return $this->title;
  }

  public function description ($description) {
    $this->description = $description;
  }

  public function keywords ($keywords) {
    $this->keywords = $keywords;
  }

  public function robots ($robots) {
    if (is_bool($robots)) $this->robots = $robots;
  }

  public function link ($link, $prepend=false) {
    if (!is_array($link)) $link = array($link);
    if ($prepend) {
      $this->include = array_merge($link, $this->include);
    } else {
      foreach ($link as $value) $this->include[] = $value;
    }
  }

  public function css ($link, $media='', $ie='') {
    if (empty($media)) $media = 'all';
    $link = '<link rel="stylesheet" type="text/css" media="' . $media . '" href="' . $this->path($link) . '" />';
    if (!empty($ie)) $link = '<!--[if ' . $ie . ']>' . $link . '<![endif]-->';
    $this->css[] = $link;
  }

  public function jquery ($code, $oneliner=true) {
    if ($oneliner) $code = $this->oneliner($code);
    $this->jquery[] = $code;
  }

  public function body ($body) {
    if (!empty($body)) $this->body = ' ' . $body;
  }

  public function vars ($var, $function='', $prepend=false) {
    if (!isset($this->vars[$var])) $this->vars[$var] = '';
    if ($prepend) {
      $this->vars[$var] = $this->capture($function) . $this->vars[$var];
    } else { // append
      $this->vars[$var] .= $this->capture($function);
    }
  }

  public function get ($var) {
    $html = "\n<!-- begin {$var} -->\n";
    if (isset($this->vars[$var])) {
      $html .= '<div id="' . $var . '">' . $this->vars[$var] . '</div>';
      unset ($this->vars[$var]);
    }
    $html .= "\n<!-- end {$var} -->";
    return $html;
  }

  public function display ($content='') {
    $html = $this->doctype . "\n";
    $html .= '<html ' . $this->capture('language_attributes');
    if ($this->xhtml) $html .= ' xmlns="http://www.w3.org/1999/xhtml"';
    $html .= '>' . "\n";
    if ($this->doctype == '<!DOCTYPE html>') {
      $html .= '<head>' . "\n";
      $html .= '<link rel="profile" href="http://gmpg.org/xfn/11" />' . "\n";
    } else {
      $html .= '<head profile="http://gmpg.org/xfn/11">' . "\n";
    }
    $html .= $this->meta_tags();
    $html .= $this->include_scripts();
    $html .= $this->capture('wp_head');
    $html .= '</head>' . "\n";
    $html .= '<body ' . $this->capture('body_class') . $this->body . '>';
    $html .= "\n" . $content . $this->capture('wp_footer');
    $html .= "\n</body>";
    $html .= "\n</html>";
    if (!$this->xhtml) $html = str_replace(' />', '>', $html);
    return $html;
  }

  public function capture ($function='') {
    $html = '';
    if (!empty($function)) {
      $array = (!is_array($function)) ? array($function) : $function;
      $function = array_shift($array);
      if (function_exists($function)) {
        call_user_func_array($function, $array);
      } else {
        echo $function;
      }
    }
    do { $html .= ob_get_clean(); } while (ob_get_level());
    ob_start("ob_gzhandler");
    return $html;
  }

  private function meta_tags () {
    $tags = '';
    $tags .= '<meta http-equiv="Content-Type" content="' . get_bloginfo('html_type') . '; charset=' . get_bloginfo('charset') . '" />' . "\n";
    $tags .= '<title>' . $this->title . '</title>' . "\n";
    if (!empty($this->description)) {
      $tags .= '<meta name="description" content="' . $this->description . '" />' . "\n";
    }
    if (!empty($this->keywords)) {
      $tags .= '<meta name="keywords" content="' . $this->keywords . '" />' . "\n";
    }
    if (!$this->robots) {
      $tags .= '<meta name="robots" content="noindex, nofollow" />' . "\n";
    }
    return $tags;
  }

  private function include_scripts () {
    $scripts = $this->combine_scripts($this->sort_scripts($this->include));
    if (!empty($this->jquery)) {
      $this->jquery = array_unique($this->jquery);
      $scripts .= '<script type="text/javascript">' . "\n";
      $scripts .= '/* <![CDATA[ */' . "\n";
      $scripts .= 'jQuery(document).ready(function($) {' . "\n";
      $scripts .= implode("\n  ", $this->jquery) . "\n";
      $scripts .= '});' . "\n";
      $scripts .= '/* ]]> */' . "\n";
      $scripts .= '</script>' . "\n";
    }
    return $scripts;
  }
  
  private function sort_scripts ($array) { // used in $this->include_scripts()
    $array = array_unique($array);
    $scripts = array();
    foreach ($array as $script) {
      $parts = explode('.', $script);
      $ext = array_pop($parts);
      $name = implode('.', $parts);
      switch ($ext) {
        case 'ico': $scripts['ico'] = $script; break;
        case 'css': $scripts['css'][] = $name; break;
        case 'js': $scripts['js'][] = $name; break;
        default: $scripts['other'][] = $script; break;
      }
    }
    return $scripts;
  }
  
  private function combine_scripts ($sorted) { // used in $this->include_scripts()
    if (empty($sorted)) return '';
    $scripts = array();
    if (isset($sorted['ico'])) {
      $scripts[] = '<link rel="shortcut icon" type="image/x-icon" href="' . $this->path($sorted['ico']) . '" />';
    }
    if (isset($sorted['css'])) {
      foreach ($sorted['css'] as $script) {
        $scripts[] = '<link rel="stylesheet" type="text/css" media="all" href="' . $this->path($script.'.css') . '" />';
      }
    }
    $scripts[] = '<link rel="stylesheet" type="text/css" media="all" href="' . get_stylesheet_uri() . '" />';
    $scripts[] = '<link rel="pingback" href="' . get_bloginfo('pingback_url') . '" />';
    if (!empty($this->css)) $scripts = array_merge($scripts, $this->css);
    if (isset($sorted['js'])) {
      $defaults = array('scriptaculous-root', 'scriptaculous-builder', 'scriptaculous-dragdrop', 'scriptaculous-effects', 'scriptaculous-slider', 'scriptaculous-sound', 'scriptaculous-controls', 'scriptaculous', 'cropper', 'swfobject', 'swfupload', 'swfupload-degrade', 'swfupload-queue', 'swfupload-handlers', 'jquery', 'jquery-form', 'jquery-color', 'jquery-ui-core', 'jquery-ui-tabs', 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-selectable', 'jquery-ui-resizable', 'jquery-ui-dialog', 'interface', 'schedule', 'suggest', 'thickbox', 'jquery-hotkeys', 'sack', 'quicktags', 'farbtastic', 'colorpicker', 'tiny_mce', 'prototype', 'autosave', 'wp-ajax-response', 'wp-lists', 'common', 'editor', 'editor-functions', 'ajaxcat', 'admin-categories', 'admin-tags', 'admin-custom-fields', 'password-strength-meter', 'admin-comments', 'admin-users', 'admin-forms', 'xfn', 'upload', 'postbox', 'slug', 'post', 'page', 'link', 'comment', 'admin-gallery', 'media-upload', 'admin-widgets', 'word-count', 'wp-gears', 'theme-preview');
      foreach ($sorted['js'] as $script) {
        if (in_array($script, $defaults)) {
          wp_enqueue_script($script);
        } else {
          $handle = explode('/', $script);
          $handle = array_pop($handle);
          wp_enqueue_script($handle, $this->path($script.'.js'));
        }
      }
    }
    if (isset($sorted['other'])) $scripts = array_merge($scripts, $sorted['other']);
    return implode("\n", $scripts) . "\n";
  }
  
  private function path ($file) { // used id $this->combine_scripts() and $this->css()
    if ($file[0] == '/') return get_stylesheet_directory_uri() . $file; // in the current theme's directory
    if (substr($file, 0, 3) == '../') return get_template_directory_uri() . substr($file, 2); // in the parent theme's directory
    return $file; // I hope you know what you're doing
  }
  
  private function oneliner ($code) {
    return preg_replace('/\s(?=\s)/', '', str_replace(array("\r\n", "\r", "\n"), ' ', $code));
  }

}

?>